package com.pinyoumei.app.activity.wallet;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.BalanceActivity;
import com.pinyoumei.app.activity.BalanceOrderListActivity;
import com.pinyoumei.app.activity.BaseActivityCurrency;
import com.pinyoumei.app.activity.MainUIActivity;
import com.pinyoumei.app.activity.WebViewActivity;
import com.pinyoumei.app.bean.EPayBean;
import com.pinyoumei.app.bean.WxPayEntity;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.utils.EventBusUtils;
import com.pinyoumei.app.utils.PayUtils;
import com.pinyoumei.app.utils.SPUtils;
import com.pinyoumei.app.utils.SignatureUtils;
import com.pinyoumei.app.utils.ToastUtils;
import com.pinyoumei.app.utils.Utils;
import com.pinyoumei.app.utils.event.AlipayEvent;
import com.pinyoumei.app.view.MyGridView;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WalletRechargeActivity extends BaseActivityCurrency implements View.OnClickListener {

    private TextView includeTitle,wtvTvMoney,wtvTvCoupon,wtvTvAllmoney,wtvTvRecharge;
    private ImageView includeBack,wtvIvWxicon,wtvIvZhifubaoicon;
    private EditText wtvEtInput;
    private MyGridView wtvGvView;
    private int [] strs = new int[]{100,200,300,400,500,600};
    private List<WalletRechargeBean> list = null;
    private RelativeLayout wtvIvZhifubaoiconLayout,wtvIvWxiconLayout;
    private int payType = 1;
    private double buyAmount = 100;
    private double saveBuyAmount = 100;

    public static WalletRechargeActivity getInstance = null;

    @Override
    protected int layoutId() {
        return R.layout.wallet_recharge_view;
    }

    @Override
    protected void initView() {
        EventBusUtils.register(this);
        if (getInstance == null){
            getInstance = this;
        }
        includeTitle = findViewById(R.id.include_title);
        includeBack = findViewById(R.id.include_back);
        wtvTvMoney = findViewById(R.id.wtv_tv_money);
        wtvEtInput = findViewById(R.id.wtv_et_input);
        wtvGvView = findViewById(R.id.wtv_gv_view);
        wtvTvCoupon = findViewById(R.id.wtv_tv_coupon);
        wtvIvWxicon = findViewById(R.id.wtv_iv_wxicon);
        wtvIvZhifubaoicon = findViewById(R.id.wtv_iv_zhifubaoicon);
        wtvTvAllmoney = findViewById(R.id.wtv_tv_allmoney);
        wtvTvRecharge = findViewById(R.id.wtv_tv_recharge);
        wtvIvZhifubaoiconLayout = findViewById(R.id.wtv_iv_zhifubaoicon_layout);
        wtvIvWxiconLayout = findViewById(R.id.wtv_iv_wxicon_layout);

        wtvIvZhifubaoiconLayout.setOnClickListener(this);
        wtvIvWxiconLayout.setOnClickListener(this);
        includeBack.setOnClickListener(this);
        wtvIvWxicon.setOnClickListener(this);
        wtvIvZhifubaoicon.setOnClickListener(this);
        wtvTvRecharge.setOnClickListener(this);
        wtvTvMoney.setText(Utils.happy_coupon);
        wtvTvCoupon.setText("-¥"+Utils.red_package_amount);
        allMoney(buyAmount - Utils.red_package_amount);
        wtvEtInput.addTextChangedListener(textWatcher);
        findViewById(R.id.include_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initData() {
        includeTitle.setText("购买开心团券");
        list = new ArrayList<>();
        for (int i=0;i<strs.length;i++){
            WalletRechargeBean bean = new WalletRechargeBean();
            bean.setMoneyNum(strs[i]+"");
            bean.setSelect(i==0?true:false);
            list.add(bean);
        }
        WalletRechargeAdapter walletRechargeAdapter = new WalletRechargeAdapter(this,list);
        wtvGvView.setAdapter(walletRechargeAdapter);
        walletRechargeAdapter.notifyDataSetChanged();
        wtvGvView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                for (int i=0;i<list.size();i++){
                    list.get(i).setSelect(false);
                }
                list.get(position).setSelect(true);
                walletRechargeAdapter.notifyDataSetChanged();
                saveBuyAmount = strs[position];
                wtvEtInput.setText(list.get(position).getMoneyNum());
                allMoney(saveBuyAmount - Utils.red_package_amount);
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.include_back:

                break;
            case R.id.wtv_iv_wxicon_layout:
            case R.id.wtv_iv_wxicon:
                payType = 1;
                selectPayType(wtvIvWxicon);
                break;
            case R.id.wtv_iv_zhifubaoicon_layout:
            case R.id.wtv_iv_zhifubaoicon:
                payType = 2;
                selectPayType(wtvIvZhifubaoicon);
                break;
            case R.id.wtv_tv_recharge:
                String inputMoney = wtvEtInput.getText().toString();
                if (!TextUtils.isEmpty(inputMoney)){
                    int minNum = Integer.parseInt(inputMoney);
                    if(minNum < 100){
                        wtvEtInput.setText("");
                        ToastUtils.showLong("输入不能小于100");
                        return;
                    }
                }
                if(!TextUtils.isEmpty(inputMoney)){
                    buyAmount = Double.parseDouble(inputMoney);
                }else{
                    buyAmount = saveBuyAmount;
                }
                allMoney(buyAmount - Utils.red_package_amount);
                buyHappyCouponSubmit(SPUtils.getAppUserId(this));
                break;
        }
    }

    private void selectPayType(ImageView imageView){
        wtvIvWxicon.setImageResource(R.mipmap.wallet_check_no_icon);
        wtvIvZhifubaoicon.setImageResource(R.mipmap.wallet_check_no_icon);
        imageView.setImageResource(R.mipmap.wallet_check_yes_icon);
    }

    private void allMoney(double my){
        wtvTvAllmoney.setText(my+"");
    }

    public void buyHappyCouponSubmit(String user_id){
        Map<String, Object> map = new HashMap<>();
        map.put("user_id",user_id);
        map.put("buy_amount", buyAmount);
        map.put("pay_type",payType);
        OkGo.<String>post(Constants.buyHappyCouponSubmit)
                .params("user_id", user_id)
                .params("buy_amount", buyAmount)
                .params("pay_type", payType)
                .params("sign", SignatureUtils.createSignature(map, Constants.SIGN_SECRET))
                .execute(new StringCallback() {

                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        loadingDailog.show();
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        loadingDailog.dismiss();
                        EPayBean ePayBean = gson.fromJson(response.body(), EPayBean.class);
                        if (ePayBean.getCode() > 0 ){
                            switch (payType) {
                                case 1:
                                    //微信支付
                                    IWXAPI wxapi = WXAPIFactory.createWXAPI(WalletRechargeActivity.this, SPUtils.getWxKey(WalletRechargeActivity.this));
                                    PayUtils payUtils = new PayUtils(wxapi,WalletRechargeActivity.this, ePayBean.getResult().getPartner_id());
                                    WxPayEntity wxPayEntity = new WxPayEntity();
                                    wxPayEntity.setPrepay_id(ePayBean.getResult().getPrepay_id());
                                    wxPayEntity.setNoncestr(ePayBean.getResult().getNonce_str());
                                    wxPayEntity.setTimestamp(ePayBean.getResult().getTime_stamp());
                                    wxPayEntity.setSign(ePayBean.getResult().getSign());
                                    payUtils.payByWechat(wxPayEntity);
                                    break;
                                case 2:
                                    //支付宝
                                    //需要跳进支付宝H5支付页面
                                    String url = ePayBean.getResult().getAli_pay_url();
                                    if (TextUtils.isEmpty(url)) {
                                        ToastUtils.showShort("支付链接为空");
                                        finish();//一旦出现支付失败订单提交界面得销毁 订单作废 因为不能重复提交同一订单
                                        return;
                                    }

                                    Intent intent = new Intent(WalletRechargeActivity.this, WebViewActivity.class);
                                    intent.putExtra("url", url);
                                    intent.putExtra("order_title", "正在支付");
                                    startActivity(intent);
//                                    h5Pay(url);
                                    break;
                                default:
                                    break;
                            }

                        }else{
                            ToastUtils.showShort(ePayBean.getMsg());
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        loadingDailog.dismiss();
                    }
                });
    }

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(!TextUtils.isEmpty(s.toString())){
                allMoney(Double.parseDouble(s.toString()) - Utils.red_package_amount);
            }else {
                allMoney(saveBuyAmount - Utils.red_package_amount);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onMessageEventMain(AlipayEvent event) {
        //订单详情
        if (TextUtils.equals(event.is_pay,"1")){
            finish();
        }
        EventBusUtils.removeStickyEvent( AlipayEvent.class);


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtils.unregister(this);
    }
}
